package cn.fulong.smebj.admin.controller;

import cn.fulong.frame.config.Result;
import cn.fulong.smebj.entity.Answer;
import cn.fulong.smebj.entity.AnswerImg;
import cn.fulong.smebj.entity.Question;
import cn.fulong.smebj.entity.SpecialTopic;
import cn.fulong.smebj.mapper.AnswerImgMapper;
import cn.fulong.smebj.mapper.AnswerMapper;
import cn.fulong.smebj.mapper.QuestionMapper;
import cn.fulong.smebj.mapper.SpecialTopicMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Api("答题、判题")
@RestController
@RequestMapping("/answer")
public class AnswerController {
    @Autowired
    private AnswerImgMapper answerImgMapper;

    @Autowired
    private AnswerMapper answerMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Value("${application.upload-path}")
    private String uploadPath;

    @ApiOperation("管理列表")
    @RequestMapping(value = "/list")
    public Result<Object> list(Integer pageNo, Integer pageSize) {
        IPage<Map<String,Object>> iPage = new Page<>(Optional.ofNullable(pageNo).orElse(0), pageSize);
        IPage<Map<String,Object>> result = answerMapper.queryList(iPage);
        return Result.success(result);
    }


    @ApiOperation("保存答案")
    @PostMapping(value = "/save")
    public Result<Object> save(Long qid,@RequestParam("file") MultipartFile file,String content,Long userId) {
        String originalFilename = file.getOriginalFilename();
        String extPath = "/answer/"+ qid+ "/"+userId+"/"+originalFilename;
        String path = uploadPath+extPath;
        StringBuilder fileUrl = new StringBuilder("/");
        try {
            File folderFile = new File(path);
            if(!folderFile.exists()){
                String[] splitFolder = path.split("/");
                //递归创建文件夹
                for (int i = 0; i < splitFolder.length; i++) {
                    String url = splitFolder[i];
                    if(StringUtils.isEmpty(url)){
                        continue;
                    }
                    fileUrl.append(url).append("/");
                    File childUrl = new File(String.valueOf(fileUrl));
                    if(!childUrl.exists()){
                        childUrl.mkdir();
                    }
                }
            }
            file.transferTo(new File(path).getCanonicalFile());
            List<Answer> list = answerMapper.query(qid,userId);
            Answer answer = null;
            if(list.size()<=0){
                answer= new Answer();
                answer.setAnswerTime(new Date(System.currentTimeMillis()));
                answer.setContent(content);
                answer.setQuestionId(qid);
                answer.setUserId(userId);
                answer.setStatus("1");
                answerMapper.insert(answer);
            }else{
                answer = answerMapper.query(qid,userId).get(0);
                answer.setAnswerTime(new Date(System.currentTimeMillis()));
                answer.setContent(content);
                answerMapper.updateById(answer);
            }
            AnswerImg answerImg = new AnswerImg();

            answerImg.setFileName(originalFilename);
            answerImg.setFilePath(extPath);
            answerImg.setAnswerId(answer.getId());
            System.out.println("-----"+answer.getId());
            answerImg.setCreateTime(new Date(System.currentTimeMillis()));
            answerImgMapper.insert(answerImg);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success();
    }


    @ApiOperation("删除答案图片")
    @PostMapping(value = "/delete")
    public Result<Object> delete(Long id) {
        AnswerImg answerImg = answerImgMapper.selectById(id);
        String path = uploadPath + answerImg.getFilePath();
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }
        answerImgMapper.deleteById(id);
        return Result.success();
    }

    @ApiOperation("判题")
    @PostMapping(value = "/audit")
    public Result<Object> audit(Long id,String remarks,String status,@RequestParam("file") MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String extPath = "/audit/"+ id+ "/"+originalFilename;
        String path = uploadPath+extPath;
        StringBuilder fileUrl = new StringBuilder("/");
        try {
            File folderFile = new File(path);
            if(!folderFile.exists()){
                String[] splitFolder = path.split("/");
                //递归创建文件夹
                for (int i = 0; i < splitFolder.length; i++) {
                    String url = splitFolder[i];
                    if(StringUtils.isEmpty(url)){
                        continue;
                    }
                    fileUrl.append(url).append("/");
                    File childUrl = new File(String.valueOf(fileUrl));
                    if(!childUrl.exists()){
                        childUrl.mkdir();
                    }
                }
            }
            file.transferTo(new File(path).getCanonicalFile());
            Answer answer = answerMapper.selectById(id);
            answer.setRemarks(remarks);
            answer.setStatus(status);
            answer.setFileName(originalFilename);
            answer.setFilePath(extPath);
            answer.setAuditTime(new Date(System.currentTimeMillis()));
            answerMapper.updateById(answer);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return Result.success();
    }

    @ApiOperation("查看题目")
    @PostMapping(value = "/topic")
    public Result<Object> topic(Long qid) {
        Question question = questionMapper.selectById(qid);
        return Result.success(question);
    }

    @ApiOperation("查看答案")
    @PostMapping(value = "/info")
    public Result<Object> info(Long answerId,Long qid,Long userId) {
        List<Answer> answerss = answerMapper.query(qid,userId);
        List<AnswerImg> answerImgs = answerImgMapper.query(answerId);
        Map map = new HashMap<>();
        map.put("info",answerss.get(0));
        map.put("imgs",answerImgs);
        return Result.success(map);
    }

    @ApiOperation("获取答案状态")
    @PostMapping(value = "/answerStatus")
    public Result<Object> answerStatus(Long questionId,Long userId) {
        List<Answer> answers = answerMapper.query(questionId,userId);

        List<AnswerImg> answerImgs = answerImgMapper.selectByQuestion(answers.get(0).getId());

        Map map = new HashMap<>();
        map.put("answerStatus",answers.get(0).getStatus());
        map.put("imgs",answerImgs);
        return Result.success( map);
    }

}
